/**
 * Created by fangshufeng on 2017/12/8.
 */

const BaseDomain = 'http://192.168.32.120';
const Port = '3000';
const basePath = 'fetchMockData';

export let MockGET = function (urlString, parameters) {
    let fetchOptions = {
        method: 'GET',
    };

    let url = BaseDomain + ':' + Port + '/' + urlString;
    let parameterStr = requestSerializer(parameters);
    if (parameterStr.length > 0) {
        url =  url +  '?' + parameterStr;
    }
    return fetch(url, fetchOptions);
};

export let MockPOST = function (urlString, parameters) {

    let fetchOptions = {
        method: 'POST',
        body:requestSerializer(parameters),
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
    };
    // console.log('请求参数:',requestSerializer(fetchOptions));
    let url = BaseDomain + ':' + Port + '/' + urlString ;
    return fetch(url, fetchOptions);
};

export let BaseDominAndPort =  BaseDomain + ':' + Port + '/';

function requestSerializer(parameters) {
    if (typeof parameters !== "object") {
        return '';
    }
    let stringKeyAndValue = '';
    let keys =  Object.keys(parameters);
    for (let i=0;i<keys.length;i++) {
        let key = keys[i];
        let value = parameters[key];
        // if (typeof(value) === 'string') {
        //     value = value.replace(/\&/g, "%26");
        // }
        if (i === keys.length-1) {
            stringKeyAndValue =  stringKeyAndValue + key + '=' + value ;
        }else  {
            stringKeyAndValue =  stringKeyAndValue + key + '=' + value + "&";
        }
    }

    return stringKeyAndValue;
}

export let BasePath = basePath;